﻿using System;
using Pfz.Extensions;

namespace Pfz.Serialization.BinaryBuiltIn
{
	/// <summary>
	/// Serializer for Byte[]
	/// </summary>
	public sealed class ByteArraySerializer:
		ItemSerializer<byte[]>
	{
		/// <summary>
		/// Gets the singleton instance.
		/// </summary>
		public static readonly ByteArraySerializer Instance = new ByteArraySerializer();

		private ByteArraySerializer()
		{
		}

		/// <summary>
		/// Reads a byte array.
		/// </summary>
		public override void Serialize(ConfigurableSerializerBase serializer, byte[] bytes)
		{
			var stream = serializer.Stream;
			stream.WriteCompressedInt32(bytes.Length);
			stream.Write(bytes);
		}

		/// <summary>
		/// Writes a byte array.
		/// </summary>
		public override byte[] Deserialize(ConfigurableSerializerBase deserializer)
		{
			var stream = deserializer.Stream;
			int size = stream.ReadCompressedInt32();
			byte[] result = new byte[size];
			stream.FullRead(result);
			return result;
		}
	}
}
